package l1j.opqlo.NewSystem.Extension;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.NewSystem.Extension.FireRoom.FireRoomThread;
import l1j.opqlo.Server.L1World.L1World;
import l1j.server.server.IdFactory;
import l1j.server.server.datatables.ItemTable;
import l1j.server.server.datatables.MapsTable;
import l1j.server.server.datatables.NpcTable;
import l1j.server.server.model.L1Location;
import l1j.server.server.model.L1NpcDeleteTimer;
import l1j.server.server.model.L1Party;
import l1j.server.server.model.L1Teleport;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.map.L1Map;
import l1j.server.server.serverpackets.S_EffectLocation;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.utils.Random;

public class TreasureMaster {
	private static TreasureMaster _instance;
	private static Logger _log = Logger.getLogger(TreasureMaster.class.getName());
//	private static int[] GameOneMap = { 9902, 9903, 9904, 9905, 9906, 9907,9908, 9909, 9910, 9911 };
	private static int[] GameTwoMap = { 260, 260, 261, 262, 263, 264 };
	private static int[] PrivateRoomMap = { 9800 };


	// private static final HashMap<Integer , Boolean>_privateRoom = new
	// HashMap<Integer , Boolean>();

	/******** 副本:冰晶洞穴 *******/
	public final static ConcurrentHashMap<Integer, IceCave> GameList2 = new ConcurrentHashMap<Integer, IceCave>();
	public final static ConcurrentHashMap<Integer, IceCave> Game2_pcList = new ConcurrentHashMap<Integer, IceCave>();

	/***************************/
	public final static ConcurrentHashMap<Integer, PrivateRoom> _privateRoom_map = new ConcurrentHashMap<Integer, PrivateRoom>();

	public static TreasureMaster getInstance() {
		if (_instance == null) {
			_instance = new TreasureMaster();
		}
		return _instance;
	}


	/** 冰晶洞穴 取得機關擺放位置 */
	public int getIceCaveBoss(final int mapid) {
		if (GameList2.containsKey(mapid)) {
			return GameList2.get(mapid).getBossCount();
		}
		return -1;
	}

	/** 冰晶洞穴 擺飾位置觸發 */
	public void IceCave(final int mapid, final int type) {
		if (GameList2.containsKey(mapid)) {
			if (type == 1) {// 下
				GameList2.get(mapid).StageMaster(3, 1);
			} else if (type == 2) {// 上
				GameList2.get(mapid).StageMaster(6, 1);
			} else if (type == 3) {// 中
				GameList2.get(mapid).StageMaster(10, 1);
			}
		}
	}

	/** 冰晶洞穴重新加入副本用 **/
	public boolean ReJoinQuest2(final L1PcInstance pc) {
		if (Game2_pcList.containsKey(pc.getName())) {
			final IceCave ice = Game2_pcList.get(pc.getName());
			if (ice == null) {
				pc.sendPackets(new S_SystemMessage("這個副本已經結束了。"));
				Game2_pcList.remove(pc.getName());
				pc.inQuestGame = false;
			}else{
				// 32870, 32832
				if (ice.addPcList(pc)) {
					L1Teleport.teleportByMagic(pc, 32870, 32832, (short) ice._mapid, 6,true);
					return true;
				} else {
					pc.sendPackets(new S_SystemMessage("你已經在副本中或是程式正忙碌中，請稍後再試。"));
				}
			}
			//		} else if(Game1_pcList.containsKey(pc.getName())){
			//			final FireTest fire = Game1_pcList.get(pc.getName());
			//			if(fire == null){
			//				pc.sendPackets(new S_SystemMessage("這個副本已經結束了。"));
			//				Game1_pcList.remove(pc.getName());
			//				pc.inQuestGame = false;
			//				return;
			//			}
		}
		return false;
	}

	/*
	 * public TreasurMaster(){ _privateRoomMap.put( 1 , );
	 *
	 * }
	 */
	public void RemoveGameList(final int mapid) {

		if (GameList2.containsKey(mapid)) {
			GameList2.remove(mapid);
		} else if (_privateRoom_map.containsKey(mapid)) {
			_privateRoom_map.remove(mapid);
		}
	}

	/** BOSS1死亡時重置副本 */
	public void RemoveTreasure(final int mapid, final int npcid) {
	 if (GameList2.containsKey(mapid)) {
			GameList2.get(mapid).npdDead(npcid);
		}else{
			FireRoomThread.get().bossDead(mapid, npcid);;
		}
	}

	// 召喚用
	public L1NpcInstance[] spawn(final int Itemid, final int npcId,
			final int count, final int X, final int Y, final short mapId,
			final int randomRange, final int timeMillisToDelete,
			final boolean isBOSS) {
		boolean AreaSpawn = false;
		final L1NpcInstance[] _npc = new L1NpcInstance[count];
		if (X == 0 || Y == 0) {
			AreaSpawn = true;
		}
		int locx1 = 0, locx2 = 0, locy1 = 0, locy2 = 0, RandomNpcGetItem = 0;
		L1ItemInstance item = null;
		if (Itemid > 0) {
			item = ItemTable.getInstance().createItem(Itemid);
		}
		if (AreaSpawn) {
			final int[] mapXY = MapsTable.getInstance().getTemplate(mapId);
			locx1 = mapXY[0];
			locx2 = mapXY[1];
			locy1 = mapXY[2];
			locy2 = mapXY[3];
		}
		if (item != null) {
			RandomNpcGetItem = Random.nextInt(count) + 1;
		}
		L1NpcInstance npc = null;
		for (int i = 0; i < count; i++) {
			try {
				npc = NpcTable.getInstance().newNpcInstance(npcId);
				npc.setId(IdFactory.getInstance().nextId());
				npc.setMap(mapId);
				if (isBOSS) {
					npc.isQuestMob = true;
					final S_EffectLocation packet1 = new S_EffectLocation(32845, 32832, 761);
					npc.broadcastPacketAll(packet1);
				}

				if (randomRange == 0 && count == 1) {
					npc.setX(X);
					npc.setY(Y);
					if (item != null) {
						item.setCount(1);
						npc.getInventory().storeItem(item);
					}
				} else {
					int tryCount = 0;
					do {
						if (item != null) {
							if (i == RandomNpcGetItem) {// 創造通關道具至NPC身上
								item.setCount(1);
								npc.getInventory().storeItem(item);
								item = null;
							}

						}
						if (AreaSpawn) {
							final L1Map map = npc.getMap();
							final int rangeX = locx2 - locx1;
							final int rangeY = locy2 - locy1;
							npc.setX(Random.nextInt(rangeX) + locx1);
							npc.setY(Random.nextInt(rangeY) + locy1);
							final L1Location location = npc.getLocation();
							if (map.isInMap(location)
									&& map.isPassable(location)) {
								break;
							}
						} else {
							tryCount++;
							npc.setX(X + Random.nextInt(randomRange)- Random.nextInt(randomRange));
							npc.setY(Y + Random.nextInt(randomRange)- Random.nextInt(randomRange));
							final L1Location location = npc.getLocation();
							final L1Map map = npc.getMap();
							if (map.isInMap(location)
									&& map.isPassable(location)) {
								break;
							}
						}
						Thread.sleep(1);
					} while (tryCount < 50);

					if (tryCount >= 50) {
						npc.setX(X);
						npc.setY(Y);
					}
				}
				npc.addHitup(500);
				npc.setHomeX(npc.getX());
				npc.setHomeY(npc.getY());
				npc.setHeading(Random.nextInt(8));
				// npc.setPortalNumber(portalNumber);

				L1World.getInstance().storeObject(npc);
				L1World.getInstance().addVisibleObject(npc);
				/*
				 * if (npc.getGfxId() == 7548 || npc.getGfxId() == 7550 ||
				 * npc.getGfxId() == 7552 || npc.getGfxId() == 7554 ||
				 * npc.getGfxId() == 7585 || npc.getGfxId() == 7539 ||
				 * npc.getGfxId() == 7557 || npc.getGfxId() == 7558 ||
				 * npc.getGfxId() == 7864 || npc.getGfxId() == 7869 ||
				 * npc.getGfxId() == 7870) {
				 * npc.npcSleepTime(ActionCodes.ACTION_AxeWalk,
				 * L1NpcInstance.ATTACK_SPEED); for (final L1PcInstance pc :
				 * L1World.getInstance().getVisiblePlayer(npc)) {
				 * npc.onPerceive(pc); final S_DoActionGFX gfx = new
				 * S_DoActionGFX(npc.getId(), ActionCodes.ACTION_AxeWalk);
				 * pc.sendPackets(gfx); } }
				 */

				npc.turnOnOffLight();
				npc.startChat(L1NpcInstance.CHAT_TIMING_APPEARANCE); // チャット開始

				if (timeMillisToDelete > 0) {
					final L1NpcDeleteTimer timer = new L1NpcDeleteTimer(npc,timeMillisToDelete);
					timer.begin();
				}
				_npc[i] = npc;
			} catch (final Exception e) {
				_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
			}
		}
		return _npc;
	}

	public void TreasureBegin(final L1PcInstance pc, final int type,
			final boolean needParty, final int ItemId) {

		if (needParty) {
			if (!pc.isInParty()) {
				pc.sendPackets(new S_SystemMessage("你沒有組隊。"));
				return;
			}
			final L1Party party = pc.getParty();
			if (!party.isLeader(pc)) {
				pc.sendPackets(new S_SystemMessage("你不是隊長。"));
				return;
			}
			// if(party.getLock()){return;}
			// party.setLock(true);
		}
		boolean MapisOK = false;
		/**
		 * pc , mapid , xy[] , itemid , totaltime , npcid[] , npccount[] ,
		 * npcswawnX[] , npcswawnY[]
		 */
		switch (type) {
		case 2:// 冰晶副本
			for (final int mapid : GameTwoMap) {
				if (!GameList2.containsKey(mapid)) {
					final int objid = pc.getId();
					if (Game2_pcList.containsKey(objid)) {
						final IceCave Srcice = Game2_pcList.get(objid);
						final List<String>pcName = Srcice._pcNameList;
						if(pcName !=null && pcName.contains(pc.getName())){
							pcName.remove(pc.getName());
						}
						Game2_pcList.remove(objid);
					}
					final IceCave ice = new IceCave(pc, mapid, false);
					GameList2.put(mapid, ice);
					MapisOK = true;
					break;
				}
			}
			break;
		case 4:// 掛網房間
			for (final int mapid : PrivateRoomMap) {
				if (!_privateRoom_map.containsKey(mapid)) {
					_privateRoom_map.put(mapid, new PrivateRoom(pc, 0));
					MapisOK = true;
					break;
				}
			}
		}
		if (!MapisOK) {
			pc.sendPackets(new S_SystemMessage("目前副本地圖已經全部額滿，請稍後再嘗試。"));
			return;
		}
		pc.getInventory().removeItemByItemId(ItemId, 1);
	}
}
